import copy

from django.http import HttpResponse, JsonResponse
from rest_framework_jwt.settings import api_settings
from django.contrib.auth.hashers import make_password
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .Ser import *
from .models import JWTUser
from rest_framework.permissions import IsAuthenticated, AllowAny

from dwebsocket.decorators import accept_websocket
import json

from .db import db1


# Create your views here.


class JWTUserApi(APIView):
    def post(self, request):
        # 获取数据，密码加密并保存到数据库
        data = request.data
        dict = copy.deepcopy(data)
        old_pwd = data.get('password')
        ser_pwd = make_password(old_pwd)
        dict['password'] = ser_pwd
        data1 = JWTUserModels(data=dict)
        data1.is_valid()
        data1.save()

        # 生成token
        user = JWTUser.objects.get(username=dict['username'])
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        print(token)

        # 将token和数据库的用户信息进行返回
        response_data = data1.data
        response_data['JWTToken'] = token

        return Response({'code': 200, 'data': response_data})


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username': user.username,
        'userid': user.id
    }


class TestApi(APIView):
    parser_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'meg': '你可以访问'})


class Test2Api(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'meg': '你登录了，才可以访问'})


# 存储连接websocket的用户
clients = {}


@accept_websocket
def websocketLink(request):
    # 获取连接
    if request.is_websocket:
        # 新增 用户  连接信息
        clients['admin'] = request.websocket
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break


# 发送消息
def websocketMsg(client, msg):
    b1 = json.dumps(msg, ensure_ascii=False).encode('utf-8')
    client.send(b1)


# 服务端发送消息


def send(request):
    # redis
    # if clients:
    #     for i in clients:
    websocketMsg(clients['admin'], {'title': '您有新的订单了'})
    return HttpResponse("ok")


def cust(self):
    sql = "select c.id,c.name,c.tmoney,c.company_name,c.status from customer as c left join reg_form as" \
          " rf on c.refromid=rf.id left join customer_manager as cm on cm.id=c.manager_id"
    res = db1.findall(sql)

    return JsonResponse({'code': 200, 'list': res})


import json


def audit(request):
    import time
    # 获取参数
    data = json.loads(request.body)
    time = int(time.time())
    ssql = "select * from customer where id=%d" % (int(data['id']))
    customer = db1.find(ssql)

    # 更新constmer表，状态，审核人，审核时间
    sql = "update customer set status=%d,audit_time=%d,audit_name='zs' where id=%d" % (
        int(data['is_agree']), time, int(data['id']))
    db1.update(sql)

    # 更新来源表
    sql1 = "select id,tcount from reg_form where id=%d" % (int(customer['refromid']))
    regform = db1.find(sql1)
    number = int(regform['tcount']) + 1
    sql2 = 'update reg_form set tcount=%d where id=%d' % (int(number), int(customer['refromid']))
    db1.update(sql2)
    # 更新客户经理中的总金额
    sql3 = "select * from customer_manager where id=%d" % (int(customer['manager_id']))
    manager = db1.find(sql3)
    number = int(manager['tmoney']) + int(customer['tmoney'])

    sql4 = 'update customer_manager set tmoney=%d where id=%d' % (int(number), int(customer['manager_id']))
    db1.update(sql4)
    return JsonResponse({"code": 200})
